__author__ = 'x0r'
from daemon import Daemon
from settings import Settings
import threading
import pthreadWorker
import sthreadWorker
import os
import log
import time



class goodMon(Daemon):
    def run(self):
        print "Starting magentd daemon."
        thread1 = None  # SYNC thread
        thread2 = None  # POLLER thread

        conf = Settings('magentd.conf')

        # Start logging things
        logger = log.Logger(conf.value["log"])

        # Prepare named pipe for communication between
        # sync and poller threads.
        # One way communication: sync writes -- poller reads.

        pipe_r = ''
        # Check if we have a pipe already and remove it.
        if os.path.exists ("magentd.fifo"):
            try:
                os.remove("magentd.fifo")
                logger.log("Found previous pipe: removed")
            except OSError as err:
                logger.log("ERROR: can't delete previous pipe: %s" % err.strerror)
                exit (1)

        # Make a new one
        try:
            pipe = os.mkfifo("magentd.fifo")
            logger.log("Created new pipe: magentd.fifo")
        except OSError as err:
            logger.log("ERROR: can't create pipe: %s" % err.strerror)
            exit (1)

        # Open pipe and start listening on it
        try:
            pipe_r = os.open ("magentd.fifo", os.O_RDONLY|os.O_NONBLOCK)
            print "Opened pipe for reading"
        except OSError, e:
            print "ERROR: Cant open pipe for reading: %s" % e.strerror

        # Now when pipe is opened from reading side, we can start sync thread
        print "Starting sync thread..."
        thread1 = sthreadWorker.ThreadWorker()
        logger.log("Starting 'sync' thread")
        #thread1._set_daemon()
        thread1.start()
        # thread.join()

        # Read control messages from pipe
        isPollerThreadRunning = False

        while True:
            # Give sync thread some time to initialize
            time.sleep(float(1))
            Msg = ''
            try:
                Msg = os.read(pipe_r,64)
            except OSError:
                pass
            if Msg =="BEGIN":
                if not isPollerThreadRunning:
                    print "Got BEGIN, starting poller "
                    thread2 = pthreadWorker.ThreadWorker(thread1.agentMetrics)
                    #thread2._set_daemon()
                    thread2.start()
                    isPollerThreadRunning = True
                else:
                    print "Got BEGIN again but poller is already running "

            if Msg == "STOP":
                if isPollerThreadRunning:
                    print "Got STOP, stopping poller"
                    thread2.__terminate = True
                    # Give poller thread some time to stop
                    print "Poller termination started..."
                    while thread2.isAlive():
                        pass
                    print "Poller thread termination finished..."
                    isPollerThreadRunning = False
                else:
                    print "Got STOP but poller is not started."


            else:
                print "No msg received"
                if not isPollerThreadRunning:
                    exit(0)
                pass

            print "Threads count: %s" % threading.active_count()
            time.sleep(float(1))
